package ai.people.netmon.auth.service;

import ai.people.core.feign.api.system.SystemFeignClient;
import ai.people.core.security.entity.AuthenticationUser;
import ai.people.netmon.framework.domain.system.request.UpdatePasswordParam;
import ai.people.netmon.framework.domain.system.vo.NmSystemUserVO;
import ai.people.netmon.framework.model.response.Result;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.stereotype.Service;

/**
 * 兼容旧用户MD5加密密码
 * 将旧密码升级为bcrypt加密方式
 *
 * @author yuanqinglong
 * @date 2022/4/11 12:10
 */
@Service
@RequiredArgsConstructor
public class UserDetailsPasswordServiceImpl implements UserDetailsPasswordService {


    Logger logger = LoggerFactory.getLogger(UserDetailsPasswordServiceImpl.class);

    /**
     * 系统客户端
     */
    private final SystemFeignClient systemFeignClient;

    /**
     * Modify the specified user's password. This should change the user's password in the
     * persistent user repository (database, LDAP etc).
     *
     * @param user        the user to modify the password for
     * @param newPassword the password to change to,
     *                    encoded by the configured {@code PasswordEncoder}
     * @return the updated UserDetails with the new password
     */
    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        AuthenticationUser authenticationUser = (AuthenticationUser) user;
        logger.info("upgrade password : {}", user.getUsername());
        Result<NmSystemUserVO> userVOResult = systemFeignClient.updatePasswordByAccount(new UpdatePasswordParam(user.getUsername(), newPassword));
        if (!userVOResult.getStatus()){
            return user;
        }
        return new AuthenticationUser(authenticationUser.getUserId(), authenticationUser.getUserRoleId(),authenticationUser.getUserRoleCode(), authenticationUser.getUsername(), authenticationUser.getUserPhone(), newPassword,
                authenticationUser.getJoinMaxCount(), authenticationUser.getLabel(), authenticationUser.getPlace(), authenticationUser.getAuthorities());
    }
}
